package com.hmdp.utils.impl;

import cn.hutool.core.lang.UUID;
import com.hmdp.utils.ILock;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class RedisLockImpl implements ILock {


    private final StringRedisTemplate stringRedisTemplate;
    private final String name;


    private static final String REDIS_PREFIX = "lock:";
    private static final String SERVICE_JVM_ID = UUID.randomUUID().toString(true) + "-";

    //定义Lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }


    public RedisLockImpl(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long setTimeout) {

        //设置当前线程的标识
        String curThreadID = SERVICE_JVM_ID + Thread.currentThread().getId();

        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(REDIS_PREFIX + name, curThreadID, setTimeout, TimeUnit.SECONDS);

        return Boolean.TRUE.equals(success);
    }


    @Override
    public void unLock() {
        //调用Lua脚本，执行Redis操作，具有原子性
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(REDIS_PREFIX + name),
                SERVICE_JVM_ID + Thread.currentThread().getId()
        );
    }
}

/*    @Override
    public void unLock() {
        String curThreadID = SERVICE_JVM_ID + Thread.currentThread().getId();
        String redisLockID = stringRedisTemplate.opsForValue().get(REDIS_PREFIX + name);
        if(curThreadID.equals(redisLockID)){
            stringRedisTemplate.delete(REDIS_PREFIX + name);
        }
    }*/

